//
//  LspNbUserAccount.swift
//  LspSwiftFinayTest
//
//  Created by lsp's mac pro on 2018/4/25.
//  Copyright © 2018年 lsp's mac pro. All rights reserved.
//

import UIKit
private let accountFile : NSString = "useracclunt.json"


class LspNbUserAccount: NSObject {
 
    var access_token :String?
    var expires_in : TimeInterval = 0{
        didSet{
            //用didset 方法监听expires_date的走向
            expires_date = Date(timeIntervalSinceNow: expires_in)
        }
        
    }
    
    var uid : String?
    
    //过期日期
    var expires_date : Date?
    
    //用户昵称
    var screen_name : String?
    
    //用户头像
    var avatar_large : String?
    
    
    
    
    
    
    override init() {
        super.init()
        //从磁盘加载保存的文件 -》字典
        //使用字典设置属性
        
        guard let overrridePath = accountFile.cz_appendDocumentDir(),
              let data = NSData.init(contentsOfFile: overrridePath),
        let dict = try? JSONSerialization.jsonObject(with: data as Data, options: [])  as? [String:AnyObject]
            else {
               return
            }
        //用户是否登录的关键
        yy_modelSet(with: dict ?? [:])
        
        //在信息的时候解释返回的东西
        if expires_date?.compare(Date()) != .orderedDescending {
            access_token=nil
            uid = nil
            _ = try? FileManager.default.removeItem(atPath: overrridePath)
        }
        
        
        
    }
    
    //每次都重写
    override var description: String{
        
        return yy_modelDescription()
    }

    //存储信息到本地
    func saveAccount() {
        //模型转字典
        var dict = (self.yy_modelToJSONObject() as? [String: AnyObject]) ?? [:]
        //删除 expires_in
        dict.removeValue(forKey: "expires_in")
        
        //guard let守护需要存储的信息和路径
        guard let data = try? JSONSerialization.data(withJSONObject: dict, options: []),let filePath = accountFile.cz_appendDocumentDir()
            
            else {
            return
        }
        
 //data存储到本地
        (data as NSData).write(toFile: filePath, atomically: true)
        
        print("用户账户保存成功 \(filePath)")
        
    }
    
    
}
